import { getRouterParam } from 'h3'
import { getAppsData } from '~/server/plugins/apps'

export default defineEventHandler(async (event) => {
    const searchQuery = getRouterParam(event, 'searchQuery')
    const query = getQuery(event)
    const page = Number(query.page) || 1
    
    try {
        // 从内存中获取所有应用数据
        const allApps = getAppsData()
        let totalPages = Math.ceil(allApps.length / 10)

        if (searchQuery) {
            // 根据搜索关键词过滤应用
            const resultApps = allApps.filter(app => {
                return app?.name?.toLowerCase().includes(searchQuery.toLowerCase())
            })
            totalPages = Math.ceil(resultApps.length / 10)
            return {
                totalPages,
                apps: resultApps.slice((page - 1) * 10, page * 10)
            }
        }
        
        return {
            totalPages,
            apps: allApps.slice((page - 1) * 10, page * 10)
        }
    } catch (error) {
        console.error('Error reading apps:', error)
        return {
            totalPages: 0,
            apps: []
        }
    }
})